package org.qufenqi.api.service.impl;

import com.alibaba.fastjson.support.odps.udf.CodecCheck;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.qufenqi.api.common.CommonResponse;
import org.qufenqi.api.entity.*;
import org.qufenqi.api.mapper.*;
import org.qufenqi.api.service.BuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service("BuyService")
public class BuyServiceImpl implements BuyService {
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private InstalmentMapper instalmentMapper;
    @Autowired
    private QuotaMapper quotaMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public CommonResponse<Address> getAddress(String id) {
        Address address = addressMapper.selectById(id);
        if(address == null)
            return CommonResponse.responseForErrorMessage("用户没有添加过地址");
        return CommonResponse.responseForSuccess(address);
    }
    //全款
    @Override
    public CommonResponse<String> fullPurchase(String userId, String itemId,int num) {
        Account account = accountMapper.selectById(userId);
        Item item = itemMapper.selectById(itemId);
        if(account.getUsermoney()<item.getPrice() * num){
            return CommonResponse.responseForErrorMessage("余额不足，请充值");
        }

        //redis字符串序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        //添加订单
        if(item.getReserve() < num)
            return CommonResponse.responseForErrorMessage("库存不足，请修改数量");
        Order order = new Order();
        //日期
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//格式化
        Date date = new Date();
        order.setOrderdate(sdf.format(date));
        order.setItemid(itemId);
        order.setUserid(userId);
        order.setTotalprice(item.getPrice() * num);
        orderMapper.insert(order);

        try {
            redisTemplate.delete(order.getOrderid() + "Order");
            redisTemplate.delete(order.getUserid()+"Cart");
        }
        catch (Exception ex){
            System.out.println("无缓存，不需要删除");
        }

        //修改商品数量
        UpdateWrapper<Item> wrapper = new UpdateWrapper<>();
        int reserve = item.getReserve()-num;
        wrapper.eq("itemid",itemId).set("reserve",reserve);
        itemMapper.update(null,wrapper);
        //修改余额
        UpdateWrapper<Account> wrapper1 = new UpdateWrapper<>();
        wrapper1.eq("userid",userId).set("usermoney",account.getUsermoney()-item.getPrice()*num);
        accountMapper.update(null,wrapper1);
        return CommonResponse.responseForSuccess();
    }
    //分期
    @Override
    public CommonResponse<String> instalment(String userId, String itemId) {
        //redis字符串序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        Item item = itemMapper.selectById(itemId);
        Quota quota = quotaMapper.selectById(userId);
        if(quota.getQuota()<item.getPrice())
            return CommonResponse.responseForErrorMessage("分期额度不足");
        //创建日期
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//格式化
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH,1);//月份加一
        //创建订单

        Order order = new Order();
        order.setOrderdate(sdf.format(date));
        order.setItemid(itemId);
        order.setUserid(userId);
        order.setTotalprice(item.getPrice());
        orderMapper.insert(order);

        try {
            redisTemplate.delete(order.getOrderid() + "Order");
            redisTemplate.delete(order.getUserid()+"Cart");
        }
        catch (Exception ex){
            System.out.println("无缓存，不需要删除");
        }


        //修改商品数量
        UpdateWrapper<Item> wrapper = new UpdateWrapper<>();
        int reserve = item.getReserve()-1;
        wrapper.eq("itemid",itemId).set("reserve",reserve);
        itemMapper.update(null,wrapper);
        //生成分期单
        Instalment instalment = new Instalment();
        instalment.setUserId(userId);
        Date date1 = calendar.getTime();
        instalment.setCalendar(sdf.format(date1));
        instalment.setOrderId(order.getOrderid());
        instalment.setNextPrice(item.getPrice()/12);
        instalment.setTotalPrice(item.getPrice());
        instalmentMapper.insert(instalment);
        UpdateWrapper<Quota> wrapper1 = new UpdateWrapper<>();
        wrapper1.eq("user_id",userId).set("quota",quota.getQuota()-item.getPrice());
        quotaMapper.update(null,wrapper1);
        return CommonResponse.responseForSuccess();
    }

    @Override
    public CommonResponse<List<Instalment>> getRepaymentList(String userId) {
        QueryWrapper<Instalment> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).gt("total_price",0);
        List<Instalment> list ;
        list = instalmentMapper.selectList(wrapper);
        if(list.isEmpty())
            return CommonResponse.responseForErrorMessage("用户没有分期");
        return CommonResponse.responseForSuccess(list);
    }

    //还款
    @Override
    public CommonResponse<String> repayment(String instalmentid) throws ParseException {

        //进行还款

        Instalment instalment = instalmentMapper.selectById(instalmentid);
        Account account = accountMapper.selectById(instalment.getUserId());
        if(account.getUsermoney()<instalment.getNextPrice())
            return CommonResponse.responseForErrorMessage("余额不足，请充值");

        //还款成功

        Quota quota = quotaMapper.selectById(instalment.getUserId());

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//格式化
        Date date = sdf.parse(instalment.getCalendar());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH,1);//月份加一
        date = calendar.getTime();

        UpdateWrapper<Instalment> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",instalmentid)
                .set("total_price", instalment.getTotalPrice()-instalment.getNextPrice())
                .set("calendar",sdf.format(date));
        instalmentMapper.update(null,wrapper);

        UpdateWrapper<Quota> wrapper1 = new UpdateWrapper<>();
        wrapper1.eq("user_id",instalment.getUserId()).set("quota",quota.getQuota()+instalment.getNextPrice());
        quotaMapper.update(null,wrapper1);

        UpdateWrapper<Account> wrapper2 = new UpdateWrapper<>();
        wrapper2.eq("userid",account.getUserId()).set("usermoney",account.getUsermoney()-instalment.getNextPrice());
        accountMapper.update(null,wrapper2);
        return CommonResponse.responseForSuccess();
    }
}
